package nbcp.base.config

import nbcp.base.comm.OpenAction
import nbcp.base.comm.SystemContext

import nbcp.base.utf8
import nbcp.db.LoginUserModel
import nbcp.web.HttpContext
import nbcp.web.LoginUser
import nbcp.web.MyHttpRequestWrapper
import nbcp.web.MyHttpResponseWrapper
import org.springframework.context.annotation.Configuration
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import java.lang.Exception
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by yuxh on 2019/1/17
 */
@Configuration
class MyInterceptor : HandlerInterceptorAdapter() {
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {

        if (request is MyHttpRequestWrapper == false) {
            return true
        }
        if (response is MyHttpResponseWrapper == false) {
            return true
        }

        var anns = (handler as HandlerMethod).beanType.annotations
        var isOpenAction = anns.any {  OpenAction::class.java.isAssignableFrom(it.javaClass) }
        if (isOpenAction) {
            return true
        }

        var loginUserModel = request.session.getAttribute(SystemContext.loginSessionKey) as LoginUserModel?
        if (loginUserModel != null) {
            request.LoginUser = loginUserModel;
        }

        if (request.LoginUser.id.isEmpty()) {
            response.status = 401;
            response.contentType = "text/plain;charset=UTF-8";
            response.outputStream.write("您需要登录".toByteArray(utf8));
            return false;
        }

        return super.preHandle(request, response, handler)
    }
}